<template>
  <el-dialog title="分配角色" :visible="visible" width="800px" @close="onCloseDialog">
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in enabledRoleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <el-row type="flex" justify="center" style="margin-top: 30px;">
      <el-button type="primary" size="middle" style="margin-right: 20px;" @click="onSaveAssignRole">确定</el-button>
      <el-button size="middle" @click="onCloseDialog">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { getEnabledRoleListAPI } from '@/api/role'
import { getEmployeeDetailAPI, assignRolesAPI } from '@/api/employee'
export default {
  name: 'AssignRole',
  data() {
    return {
      visible: false, // 控制弹窗的显示与隐藏
      enabledRoleList: [], // 已启用的角色列表
      userId: '', // 当前被分配角色的员工的id
      roleIds: [] // 被选择的角色id列表
    }
  },
  created() {
    // 获取已启用的角色列表
    this.getEnabledRoleList()
  },
  methods: {
    // 获取已启用的角色列表
    async getEnabledRoleList() {
      this.enabledRoleList = await getEnabledRoleListAPI()
    },
    // 获取当前员工的角色列表
    async getEmployeeRoleIds() {
      const { roleIds } = await getEmployeeDetailAPI(this.userId)
      this.roleIds = roleIds
    },
    // 保存分配角色
    async onSaveAssignRole() {
      await assignRolesAPI({ id: this.userId, roleIds: this.roleIds })
      this.$message.success('分配角色成功')
      // 关闭弹窗，清空数据
      this.onCloseDialog()
    },
    // 打开弹窗
    async open(id) {
      this.userId = id
      // 获取当前员工的角色列表
      await this.getEmployeeRoleIds()
      // 为了显示效果，先获取数据再打开弹窗
      this.visible = true
    },
    // 关闭弹窗，清空数据
    onCloseDialog() {
      this.visible = false
      this.roleIds = []
      this.userId = ''
    }
  }
}
</script>

<style>

</style>
